<template>
	<div class="system-user-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="80%" height="100%">
			<el-form ref="articleDialogFormRef" :model="state.ArticleForm" size="default" label-width="90px">
				<el-row :gutter="35">
          <el-input class="hide-input"></el-input>
          <el-input type="password" class="hide-input"></el-input>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="标题">
              <el-input v-model="state.ArticleForm.title" placeholder="" clearable ></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" v-if="state.dialog.type==='add'">
            <el-form-item label="文章类型">
              <el-radio-group v-model="state.ArticleForm.type">
                <el-radio :label="1">列表</el-radio>
                <el-radio :label="2">单页</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="state.ArticleForm.type === 1">
            <el-form-item label="文章类型">
              <el-cascader
                  :options="state.parents"
                  :props="{ checkStrictly: true,emitPath:false, value: 'id', label: 'name' }"
                  placeholder="选择文章分类"
                  clearable
                  style="width: 100%"
                  v-model="state.ArticleForm.articleClassifyId"
              >
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="外链">
              <el-input v-model="state.ArticleForm.url" placeholder="" clearable ></el-input>
            </el-form-item>
          </el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="作者">
							<el-input v-model="state.ArticleForm.writer" placeholder="" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="简述">
							<el-input v-model="state.ArticleForm.desc" placeholder="" type="textarea" clearable></el-input>
						</el-form-item>
					</el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="关键词">
              <el-input v-model="state.ArticleForm.keywords" placeholder="关键词" type="textarea" clearable></el-input>
            </el-form-item>
          </el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="状态">
							<el-switch v-model="state.ArticleForm.status" active-value="1" inactive-value="0" inline-prompt active-text="启" inactive-text="禁"></el-switch>
						</el-form-item>
					</el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" >
            <el-form-item label="上传封面">
              <el-upload
                  class="image-uploader"
                  :action="state.uploadImgUrl"
                  :show-file-list="true"
                  :on-success="handleUploadImageSuccess"
                  accept="image/*"
                  :headers="state.header"
                  :on-remove="clearImageValue"
                  :file-list="state.imageList"
                  list-type="picture-card"
              >
                <img v-if="state.ArticleForm.cover" :src="state.ArticleForm.cover" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon" :size="30"><ele-Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" >
            <el-form-item label="上传视频">
              <video :src="state.ArticleForm.video" controls class="video" >
                <source :src="state.ArticleForm.video" />
                不支持
              </video>
              <el-upload
                  class="video-uploader"
                  :action="state.uploadVideoUrl"
                  :show-file-list="true"
                  :on-success="handleUploadVideoSuccess"
                  :on-remove="clearValue"
                  :file-list="state.fileList"
                  accept="video/*"
                  :headers="state.header"
                  limit="1"
                  style="padding-left: 10px;width:50%;"
              >
                <el-button type="primary" size="default">上传视频</el-button>
              </el-upload>
              <el-input v-model="state.ArticleForm.video" placeholder="手动填写视频地址" clearable style="margin-top: 5px;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" >
            <el-form-item label="文章详情">
              <vue-ueditor-wrap v-model="state.ArticleForm.detail"
                                editor-id="editor"
                                :config="state.editorConfig"
                                :editorDependencies="['ueditor.config.js','ueditor.all.js']"
                                style="height:500px;"/>
            </el-form-item>
          </el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref} from 'vue';
import { useArticleApi } from '/@/api/content/article';
import { ElMessage } from 'element-plus';
import { Session } from "/@/utils/storage";


// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const articleDialogFormRef = ref();
const baseUrl = import.meta.env.VITE_API_URL;
const ENV = import.meta.env.MODE
const path = ENV === 'production'?import.meta.env.VITE_PUBLIC_PATH+'/static/UEditorPlus/':'/static/UEditorPlus/'

//console.log('ENV',ENV)

const state = reactive({
	ArticleForm: {
		id:0,//id
		title: '', // 标题
		type: 1, // 类型
		articleClassifyId: 0, // 分类ID
		writer: '', // 作者
		cover: '', // 封面
		video: '', // 视频
		desc: '', // 简述
    keywords: '', // 关键词
    url: '', // 外链
		status: '1', // 状态
    detail: '' //文章内容
	},
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
  parents: [],//分类
  header:{Authorization: Session.get('token')},//上传请求头
  uploadImgUrl: baseUrl+'AdminUpload/image',//图片上传地址
  uploadVideoUrl: baseUrl+'AdminUpload/video',//视频上传地址
  fileList:[],
  imageList: [],
  editorConfig:{
    // 后端服务地址，后端处理参考
    // https://open-doc.modstart.com/ueditor-plus/backend.html
    serverUrl: baseUrl+'AdminUpload/ueditor.html',
    serverHeaders: {
      'Authorization': Session.get('token')
    },
    UEDITOR_HOME_URL: path,
    UEDITOR_CORS_URL: path,
    initialFrameWidth: '100%',
    initialFrameHeight: 400
  }
});

// 打开弹窗
const openDialog = (type: string, row: any) => {
  state.fileList = [];
  state.imageList = [];
	if (type === 'edit') {
		var info = row;
		info = getFormData(info);
		info.status = String(info.status);
    //处理缩略图
    if(info.cover){
      state.imageList = [
        {name: info.cover.substring(info.cover.lastIndexOf('/')+1), url: info.cover}
      ];
    }
    if(info.video){
      state.fileList = [
        {name: info.video.substring(info.video.lastIndexOf('/')+1), url: info.video}
      ];
    }

		state.ArticleForm = info;
		state.dialog.title = '修改';
		state.dialog.submitTxt = '修 改';
		state.dialog.type = 'edit';
	} else {
		state.dialog.title = '新增';
		state.dialog.submitTxt = '新 增';
		state.dialog.type = 'add';

		// 清空表单
		state.ArticleForm = {
      id:0,//id
      title: '', // 标题
      type: 1, // 类型
      articleClassifyId: 0, // 分类ID
      writer: '', // 作者
      cover: '', // 封面
      video: '', // 视频
      desc: '', // 简述
      keywords: '', // 关键词
      url: '', // 外链
      status: '1', // 状态
      detail: ''
    };
	}
	state.dialog.isShowDialog = true;
  getParentData();
};
//图片成功
const handleUploadImageSuccess = (
    response:any,
    uploadFile:any
) => {
  if(!response.code){
    state.ArticleForm.cover = response.data;
    state.imageList.push({name:uploadFile.name,url:response.data});
  }else{
    ElMessage.error(response.msg);
  }

}
//视频上传成功
const handleUploadVideoSuccess = (
    response:any,
    uploadFile:any
) => {
  if(!response.code){
    state.ArticleForm.video = response.data;
    state.fileList = [
      {name:uploadFile.name,url:response.data}
    ];
  }else{
    ElMessage.error(response.msg);
  }

}
//清除值
const clearImageValue = () => {
  state.ArticleForm.cover = '';
  state.imageList = [];
}
//清除值
const clearValue = () => {
  state.ArticleForm.video = '';
  state.fileList = [];
}
//获取一级分类
const getParentData = () => {
  if(state.parents.length){
    return !1;
  }
  useArticleApi().getAdminArticleParent().then(res=>{
    if(!res.code){
      state.parents = res.data;
      console.log(res.data);
    }
  }).catch(err=>{
    console.log(err);
  });
};
//填充提交数据
const getFormData = (data: any) => {
	var newData = {} as any,i;
	for(i in state.ArticleForm){
		newData[i] = data[i];
	}
	return newData;
}
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = () => {

	useArticleApi().setAdminArticle(state.ArticleForm).then(res=>{
		if(!res.code){
			ElMessage.success(state.dialog.title+'成功');
      // 清空表单
      state.ArticleForm = {
        id:0,//id
        title: '', // 标题
        type: 1, // 类型
        articleClassifyId: 0, // 分类ID
        writer: '', // 作者
        cover: '', // 封面
        video: '', // 视频
        desc: '', // 简述
        keywords: '', // 关键词
        url: '', // 外链
        status: '1', // 状态
        detail: ''
      };
      closeDialog();
      emit('refresh');
		}
	}).catch(err=>{
		console.log(err);
	});
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>
<style>
.hide-input{
  outline: none;
  border: none;
  overflow: hidden;
  width: 0;
  height: 0;
}
.image-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.image-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.avatar-uploader-icon {
  font-size: 30px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
.video{
  width:50%;
  height: 180px;
  background-color: #000000;
}
.avatar{
  max-width: 100%;
  max-height: 120px;
}
</style>
